$("#mfile").fileinput({
    showPreview: true,
    showUpload: true,
    elErrorContainer: '#kartik-file-errors',
    uploadUrl: '/admin/upload/file?type=goods',
    allowedFileExtensions: ["jpg", "jpeg", "png", "gif"]
}).on("fileuploaded", function (event, data) {
    console.log(data);
    $("#hidpic").val(data.response.data + ";" + $("#hidpic").val());
})

$("#mfileinfo").fileinput({
    showPreview: true,
    showUpload: true,
    elErrorContainer: '#kartik-file-errors',
    uploadUrl: '/admin/upload/file?type=goods',
    allowedFileExtensions: ["jpg", "jpeg", "png", "gif"]
}).on("fileuploaded", function (event, data) {
    console.log(data);
    $("#hidinfo").val(data.response.data + ";" + $("#hidinfo").val());
})

$('#dateStart').datepicker(dateformat);
$('#dateEnd').datepicker(dateformat);
$('#dateStart2').datepicker(dateformat);
$('#dateEnd2').datepicker(dateformat);

$("#mfilepackinglist").fileinput({
    showPreview: true,
    showUpload: true,
    elErrorContainer: '#kartik-file-errors',
    uploadUrl: '/admin/upload/file?type=goods',
    allowedFileExtensions: ["jpg", "jpeg", "png", "gif"]
}).on("fileuploaded", function (event, data) {
    console.log(data);
    $("#hidpackinglist").val(data.response.data + ";" + $("#hidpackinglist").val());
})

$("#mfileafterservice").fileinput({
    showPreview: true,
    showUpload: true,
    elErrorContainer: '#kartik-file-errors',
    uploadUrl: '/admin/upload/file?type=goods',
    allowedFileExtensions: ["jpg", "jpeg", "png", "gif"]
}).on("fileuploaded", function (event, data) {
    console.log(data);
    $("#hidafterservice").val(data.response.data + ";" + $("#hidafterservice").val());
})

$("#mfileintroduction").fileinput({
    showPreview: true,
    showUpload: true,
    elErrorContainer: '#kartik-file-errors',
    uploadUrl: '/admin/upload/file?type=goods',
    allowedFileExtensions: ["jpg", "jpeg", "png", "gif"]
}).on("fileuploaded", function (event, data) {
    console.log(data);
    $("#hidintroduction").val(data.response.data + ";" + $("#hidintroduction").val());
})

function shareBonusTypeFormatter(value, row, index) {
    if (value == undefined || value == "") return "";
    else if (value == 0)
        return "无奖励";
    else if (value == 1)
        return "送积分";
    else if (value == 2)
        return "送现金";
    else if (value == 3)
        return "送优惠券";
    else return ""
}

function gtypeFormatter(value, row, index) {
    if (value == undefined || value == "") return "";
    else if (value == 1)
        return "实物产品";
    else if (value == 2)
        return "虚拟产品";
    else if (value == 3)
        return "到店服务";
    else if (value == 4)
        return "上门服务";
    else return ""
}

function sidFormatter(value, row, index) {
    if (value == undefined || value == "" || value == "0") return "平台商品";
    else if (value > 0)
        return "店铺商品";
    else return ""
}

function hasSkuFormatter(value, row, index) {
    if (value == undefined || value == "") return "否";
    else if (value == 1)
        return "是";
    else return "否";
}

function sjFormatter(value, row, index) {
    if (value == undefined || value == "") return "已下架";
    else if (value == 1)
        return "已上架";
    else return "已下架";
}

function sjactFormatter(value, row, index) {
    var state = row.state;
    var id = row.id;
    var isNav = row.isNav;
    var id = row.id;
    var pic = row.pic;
    var res = '<button data-toggle="modal" class="btn-sm btn-primary" href="list.html#modal-form" data-row=' + id + ' data-index=' + index + '>修改</button>';
    res += ' <button typ-e="button" class="btn-sm btn-danger" onclick="setpintuan(\'' + id + '\',\'' + index + '\')">设置拼团</button>';
    if (state == undefined) {
    } else if (state == 1)
        res += ' <button type="button" class="btn-sm btn-info" onclick="changeState(\'' + id + '\',-1)" >下架</button>';
    else
        res += ' <button typ-e="button" class="btn-sm btn-info" onclick="changeState(\'' + id + '\',1)" >上架</button>';
    res += ' <button typ-e="button" class="btn-sm btn-danger" onclick="deleteOne(\'' + id + '\')">删除</button>';
    if (isNav != 1 && $('#isAdmin').val() == 1)
        res += ' <button type="button" class="btn-sm btn-info" onclick="changeNavState(\'' + id + '\',1,\'' + pic + '\',\'' + id + '\')" >启用分类导航</button>';

    return res;
}

function changeNavState(id, state, pic) {
    console.log(">>>>>>>changeNavState and pic=" + pic)
    if (!pic || pic.length == 0) {
        swal({title: "设置分类导航前需上传分类图标", text: "", type: "warning"})
        return
    }
    $.ajax({
        type: 'POST',
        url: "changeNavState",
        data: {
            id: id,
            pic: pic,
            state: state
        },
        success: function () {
            swal({title: "操作成功", text: "", type: "success"})
            $('#mytable').bootstrapTable('refresh', {url: '/admin/goods/list'});
        },
        dataType: "json"
    });
}

function changeState(id, state) {
    $.ajax({
        type: 'POST',
        url: "changeState",
        data: {
            id: id,
            state: state
        },
        success: function () {
            $('#mytable').bootstrapTable('refresh', {url: '/admin/goods/list'});
        },
        dataType: "json"
    });
}

function deleteOne(id) {
    swal({
        title: '您确定要删除此行数据？',
        text: '你将无法恢复它！',
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#ed5666',
        confirmButtonText: '确定删除！',
        cancelButtonText: '取消删除！',
        confirmButtonClass: 'btn btn-success',
        cancelButtonClass: 'btn btn-danger',
        buttonsStyling: false
    }).then(function () {

        $.ajax({
            type: 'POST',
            url: "deleteOne",
            data: {
                id: id,
            },
            success: function (status) {
                if (status == 1) {
                    swal({title: "删除成功", text: "", type: "success"})
                    $('#mytable').bootstrapTable('refresh', {url: '/admin/goods/list'});
                } else {
                    swal({title: "删除失败", text: "", type: "error"})
                }
            },
            dataType: "json"
        });

    }, function (dismiss) {
        // dismiss的值可以是'cancel', 'overlay',
        // 'close', 'timer'
        if (dismiss === 'cancel') {
            swal({title: '您已取消操作！', text: '', timer: 2000})
        }
    })
}

var editsw = [];

function setpintuan(id, index) {
    var data = $('#mytable').bootstrapTable("getData")[index]
    console.log(data)
    $('#hidpgid').val(id);
    $('#modal-pintuan-form').modal();
}

/**
 * 为模态框填充数据
 */
$('#modal-form').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget); // 触发事件的按钮
    var index = button.data('index');
    var modal = $(this);
    var data = $('#mytable').bootstrapTable("getData")[index]
    console.log(data)
    if (!data) return;
    modal.find('#id').val(data.id)
    modal.find('#characteristic').val(data.characteristic)
    modal.find('#logisticsId').val(data.logisticsId)
    modal.find('#minPrice').val(data.minPrice)
    modal.find('#price').val(data.price)
    modal.find('#saleprice').val(data.saleprice)

    modal.find('#name').val(data.name)
    modal.find('#goodsNo').val(data.goodsNo)
    modal.find('#numberFav').val(data.numberFav)
    modal.find('#numberGrade').val(data.numberGrade)
    modal.find('#numberOrders').val(data.numberOrders)
    modal.find('#numberSale').val(data.numberSale)

    modal.find('#paixu').val(data.paixu)
    modal.find('#dateStart').val(data.dateStart)
    modal.find('#dateEnd').val(data.dateEnd)
    modal.find('#propertyIds').val(data.propertyIds)
    modal.find('#recommend').val(data.recommend)

    modal.find('#jifen').val(data.jifen)
    modal.find('#stores').val(data.stores)
    modal.find('#jieshao').val(data.jieshao)
    modal.find('#xiangou').val(data.xiangou)
    modal.find('#videoId').val(data.videoId)

    // 此部分需要注意：如果页面有两个以上的图片编辑
    // 该部分逻辑需要重写

    modal.find('#maxUseCoupon').val(data.maxUseCoupon)
    modal.find('#shareMount').val(data.shareMount)
    modal.find('#barcode').val(data.barcode)
    modal.find('#weight').val(data.weight)
    modal.find('#views').val(data.views)

    modal.find('#ptotal').val(data.ptotal)
    modal.find('#dateStart').val(data.dateStart)
    modal.find('#dateEnd').val(data.dateEnd)

    editsw["isMember"] == undefined ? editsw["isMember"] = new Switchery(document.querySelector('#isMember'), {color: "#1AB394"}) : ""
    if (data.isMember == 1) {
        setSwitchery(editsw["isMember"], true);
    } else {
        setSwitchery(editsw["isMember"], false);
    }
    editsw["isJifen"] == undefined ? editsw["isJifen"] = new Switchery(document.querySelector('#isJifen'), {color: "#1AB394"}) : ""
    if (data.isJifen == 1) {
        setSwitchery(editsw["isJifen"], true);
    } else {
        setSwitchery(editsw["isJifen"], false);
    }
    editsw["isCoupon"] == undefined ? editsw["isCoupon"] = new Switchery(document.querySelector('#isCoupon'), {color: "#1AB394"}) : ""
    if (data.isCoupon == 1) {
        setSwitchery(editsw["isCoupon"], true);
    } else {
        setSwitchery(editsw["isCoupon"], false);
    }
    editsw["isRecommend"] == undefined ? editsw["isRecommend"] = new Switchery(document.querySelector('#isRecommend'), {color: "#1AB394"}) : ""
    if (data.isRecommend == 1) {
        setSwitchery(editsw["isRecommend"], true);
    } else {
        setSwitchery(editsw["isRecommend"], false);
    }
    editsw["isHot"] == undefined ? editsw["isHot"] = new Switchery(document.querySelector('#isHot'), {color: "#1AB394"}) : ""
    if (data.isHot == 1) {
        setSwitchery(editsw["isHot"], true);
    } else {
        setSwitchery(editsw["isHot"], false);
    }

    photosPreviewList = getPreviewList(data.photos)
    $("#mfile2").fileinput('destroy');
    $("#mfile2").fileinput({
        showPreview: true,
        showUpload: true,
        append: true,overwriteInitial:false,
        uploadClass: "btn btn-info",
        uploadLabel: "上传",removeLabel: "移除",language: "zh",
        uploadIcon: "<i class=\"glyphicon glyphicon-upload\"></i> ",
        initialPreviewShowDelete: true,
        initialPreviewAsData: true,
        initialPreviewFileType: 'image',
        initialPreview: photosPreviewList,
        previewFileIcon: '<i class="fa fa-file"></i>',
        allowedPreviewTypes: ['image'],
        initialPreviewConfig: getPreviewConfig(data.photos, 'goods', "photos", data.id),
        elErrorContainer: '#kartik-file-errors',
        uploadUrl: '/admin/upload/file?type=goods',
        allowedFileExtensions: ["jpg", "jpeg", "png", "gif"]
    }).on("fileuploaded", function (event, data) {
        console.log(data);
        $("#hidpic2").val(data.response.data + ";" + $("#hidpic2").val());
    }).on('filedeleted', function(event, key, jqXHR, data) {
        console.log('Key = ' + key);
        $("#hidpic2").val(filedeleted($("#hidpic2").val(),key));
    })

    $("#hidpic2").val(data.photos)

    infoPreviewList = getPreviewList(data.info)
    $("#mfileinfo2").fileinput('destroy');
    $("#mfileinfo2").fileinput({
        showPreview: true,
        showUpload: true,
        append: true,overwriteInitial:false,
        uploadClass: "btn btn-info",
        uploadLabel: "上传",removeLabel: "移除",language: "zh",
        uploadIcon: "<i class=\"glyphicon glyphicon-upload\"></i> ",
        initialPreviewShowDelete: true,
        initialPreviewAsData: true,
        initialPreviewFileType: 'image',
        initialPreview: infoPreviewList,
        previewFileIcon: '<i class="fa fa-file"></i>',
        allowedPreviewTypes: ['image'],
        initialPreviewConfig: getPreviewConfig(data.info, 'goods', "info", data.id),
        elErrorContainer: '#kartik-file-errors',
        uploadUrl: '/admin/upload/file?type=goods',
        allowedFileExtensions: ["jpg", "jpeg", "png", "gif"]
    }).on("fileuploaded", function (event, data) {
        console.log(data);
        $("#hidinfo2").val(data.response.data + ";" + $("#hidpic2").val());
    }).on('filedeleted', function(event, key, jqXHR, data) {
        console.log('filedeleted Key = ' + key);
        $("#hidinfo2").val(filedeleted($("#hidinfo2").val(),key));
    })
    $("#hidinfo2").val(data.info)

    packinglistPreviewList = getPreviewList(data.packinglist)
    $("#mfilepackinglist2").fileinput('destroy');
    $("#mfilepackinglist2").fileinput({
        showPreview: true,
        showUpload: true,
        append: true,overwriteInitial:false,
        uploadClass: "btn btn-info",
        uploadLabel: "上传",removeLabel: "移除",language: "zh",
        uploadIcon: "<i class=\"glyphicon glyphicon-upload\"></i> ",
        initialPreviewShowDelete: true,
        initialPreviewAsData: true,
        initialPreviewFileType: 'image',
        initialPreview: packinglistPreviewList,
        previewFileIcon: '<i class="fa fa-file"></i>',
        allowedPreviewTypes: ['image'],
        initialPreviewConfig: getPreviewConfig(data.packinglist, 'goods', "packinglist", data.id),
        elErrorContainer: '#kartik-file-errors',
        uploadUrl: '/admin/upload/file?type=goods',
        allowedFileExtensions: ["jpg", "jpeg", "png", "gif"]
    }).on("fileuploaded", function (event, data) {
        console.log(data);
        $("#hidpackinglist2").val(data.response.data + ";" + $("#hidpackinglist2").val());
    }).on('filedeleted', function(event, key, jqXHR, data) {
        console.log('filedeleted Key = ' + key);
        $("#hidpackinglist2").val(filedeleted($("#hidpackinglist2").val(),key));
    })
    $("#hidpackinglist2").val(data.packinglist)

    afterservicePreviewList = getPreviewList(data.afterservice)
    $("#mfileafterservice2").fileinput('destroy');
    $("#mfileafterservice2").fileinput({
        showPreview: true,
        showUpload: true,
        append: true,overwriteInitial:false,
        uploadClass: "btn btn-info",
        uploadLabel: "上传",removeLabel: "移除",language: "zh",
        uploadIcon: "<i class=\"glyphicon glyphicon-upload\"></i> ",
        initialPreviewShowDelete: true,
        initialPreviewAsData: true,
        initialPreviewFileType: 'image',
        initialPreview: afterservicePreviewList,
        previewFileIcon: '<i class="fa fa-file"></i>',
        allowedPreviewTypes: ['image'],
        initialPreviewConfig: getPreviewConfig(data.afterservice, 'goods', "afterservice", data.id),
        elErrorContainer: '#kartik-file-errors',
        uploadUrl: '/admin/upload/file?type=goods',
        allowedFileExtensions: ["jpg", "jpeg", "png", "gif"]
    }).on("fileuploaded", function (event, data) {
        console.log(data);
        $("#hidafterservice2").val(data.response.data + ";" + $("#hidafterservice2").val());
    }).on('filedeleted', function(event, key, jqXHR, data) {
        console.log('filedeleted Key = ' + key);
        $("#hidafterservice2").val(filedeleted($("#hidafterservice2").val(),key));
    })
    $("#hidafterservice2").val(data.afterservice)

    introductionPreviewList = getPreviewList(data.introduction)
    $("#mfileintroduction2").fileinput('destroy');
    $("#mfileintroduction2").fileinput({
        showPreview: true,
        showUpload: true,
        append: true,overwriteInitial:false,
        uploadClass: "btn btn-info",
        uploadLabel: "上传",removeLabel: "移除",language: "zh",
        uploadIcon: "<i class=\"glyphicon glyphicon-upload\"></i> ",
        initialPreviewShowDelete: true,
        initialPreviewAsData: true,
        initialPreviewFileType: 'image',
        initialPreview: introductionPreviewList,
        previewFileIcon: '<i class="fa fa-file"></i>',
        allowedPreviewTypes: ['image'],
        initialPreviewConfig: getPreviewConfig(data.introduction, 'goods', "introduction", data.id),
        elErrorContainer: '#kartik-file-errors',
        uploadUrl: '/admin/upload/file?type=goods',
        allowedFileExtensions: ["jpg", "jpeg", "png", "gif"]
    }).on("fileuploaded", function (event, data) {
        console.log(data);
        $("#hidintroduction2").val(data.response.data + ";" + $("#hidintroduction2").val());
    }).on('filedeleted', function(event, key, jqXHR, data) {
        console.log('filedeleted Key = ' + key);
        $("#hidintroduction2").val(filedeleted($("#hidintroduction2").val(),key));
    })
    $("#hidintroduction2").val(data.introduction)

    modal.find('#cid').find("option[value='" + data['cid'] + "']").attr("selected", true);
    modal.find('#type').find("option[value='" + data['type'] + "']").attr("selected", true);
    modal.find('#gtype').find("option[value='" + data['gtype'] + "']").attr("selected", true);
    modal.find('#maxUseJifen').find("option[value='" + data['maxUseJifen'] + "']").attr("selected", true);
    modal.find('#shareBonusType').find("option[value='" + data['shareBonusType'] + "']").attr("selected", true);
})

//tableHeight函数
function tableHeight() {
    //可以根据自己页面情况进行调整
    return $(window).height() - 200;
}

$(function () {

    var sw = [];
    $(".js-switch").each(function (i, e) {
        sw[i] = new Switchery(e, {color: "#1AB394"})
    })
    $(window).resize(function () {
        $('#mytable').bootstrapTable('resetView', {
            height: tableHeight()
        })
    })

    //生成用户数据
    $('#mytable').bootstrapTable({
        method: 'get',
        url: "/admin/goods/yxlist",
        // height:520,//高度调整
        // toolbar: '#toolbar',
        striped: true, //是否显示行间隔色
        dataField: "records",
        pagination: true,//是否分页
        queryParamsType: 'limit',
        queryParams: queryParams,
        sidePagination: 'server',
        pageNumber: 1, //初始化加载第一页，默认第一页
        pageSize: 20,//单页记录数
        pageList: [20, 100, 200, 500],//分页步进值
        showExport: true,//显示导出
        showRefresh: false,//刷新按钮
        showColumns: false,
        clikToSelect: true,//是否启用点击选中行
        // toolbarAlign:'right',
        // buttonsAlign:'right',//按钮对齐方式
        columns: [
            {
                title: '全选',
                field: 'select',
                checkbox: true,
                width: 25,
                align: 'center',
                valign: 'middle'
            },
            {
                title: 'ID',
                field: 'id',
                visible: false
            },
            {
                title: '商品名',
                field: 'name'
            },
            // {
            //     title: '商品编号',
            //     field: 'goodsNo'
            // },
            {
                title: '商品原价',
                field: 'price'
            },
            {
                title: '实际售价',
                field: 'saleprice'
            },
            {
                title: '最低价',
                field: 'minPrice'
            },
            {
                title: '订单数',
                field: 'numberOrders'
            },
            {
                title: '销量数',
                field: 'numberSale'
            },
            {
                title: '总库存数',
                field: 'stores'
            },
            {
                title: '商品主图',
                field: 'pic',
                formatter: "imgFormatter"
            },

            {
                title: '支持会员卡',
                field: 'isMember',
                formatter: "sfFormatter"
            },
            {
                title: '支持积分',
                field: 'isJifen',
                formatter: "sfFormatter"
            },
            {
                title: '支持优惠券',
                field: 'isCoupon',
                formatter: "sfFormatter"
            },
            {
                title: '是否热推',
                field: 'isRecommend',
                formatter: "sfFormatter"
            },
            {
                title: '是否sku',
                field: 'hasSku',
                formatter: "hasSkuFormatter"
            },
            {
                title: '产品类型',
                field: 'gtype',
                formatter: "gtypeFormatter"
            },
            {
                title: '商品类型',
                field: 'sid',
                formatter: "sidFormatter"
            },
            {
                title: '上架状态',
                field: 'state',
                formatter: "sjFormatter"
            },
            {
                title: '操作',
                field: 'Attribute',
                align: 'center',
                width: 300,
                formatter: sjactFormatter
            }
        ],
        locale: 'zh-CN',//中文支持,
    })

    //请求服务数据时所传参数
    function queryParams(params) {
        var p = {
            limit: params.limit,
            offset: params.offset,
            sort: params.sort,
            order: params.order,
            type: 1
            , search: $('#search').val()
            , status: $('#qstatus').val()
        }
        return p;
    }

    $('#search_btn').click(function () {
        var p = {
            status: $('#qstatus').val(),
            search: $('#search').val(),
            type: 1,
            ts: new Date().getTime()
        };
        $('#mytable').bootstrapTable('refresh', p);
    })

    /*
     * 验证错误提示信息高亮
     */
    $.validator.setDefaults({
        highlight: function (e) {
            $(e).closest(".form-group").removeClass("has-success").addClass("has-error")
        }, success: function (e) {
            e.closest(".form-group").removeClass("has-error").addClass("has-success")
        }, errorElement: "span", errorPlacement: function (e, r) {
            e.appendTo(r.is(":radio") || r.is(":checkbox") ? r.parent().parent().parent() : r.parent())
        }, errorClass: "help-block m-b-none", validClass: "help-block m-b-none"
    }), $("#aform").validate(), $("#mform").validate();
})

function checkAdd() {
    $('input:checkbox').each(function (index, item) {
        if ($(this).prop("checked")) {
            $(this).val(1);
            console.log($(this).attr("name") + "=" + $(this).val())
        } else {
            $(this).val(-1);
            console.log($(this).attr("name") + "=" + $(this).val())
        }
    });
    var xg = $("#xiangou2").val();

    if (xg == "无") {
        $("#xiangou2").val(0)
    }
    if (!$.num(xg, true)) {
        return;
    }

    if ($("#hidpic").attr("required") == "required"
        && $("#hidpic").val() == "") {
        swal({title: "请上传图片", text: "", type: "warning"})
        return false;
    }

    if ($("#dateStart2").val() > $("#dateEnd2").val()) {
        swal({title: "提示", text: "拼团开始日期不能大于结束日期", type: "warning"})
        return false;
    }
    return true;
}

function checkModify() {

    $('input:checkbox').each(function (index, item) {
        if ($(this).prop("checked")) {
            $(this).val(1);
            console.log($(this).attr("id") + "=" + $(this).val())
        } else {
            $(this).val(-1);
            console.log($(this).attr("id") + "=" + $(this).val())
        }
    });

    if ($("#hidpic2").attr("required") == "required"
        && $("#hidpic2").val() == "") {
        swal({title: "请上传图片", text: "", type: "warning"})
        return false;
    }

    if ($("#dateStart").val() > $("#dateEnd").val()) {
        swal({title: "提示", text: "拼团开始日期不能大于结束日期", type: "warning"})
        return false;
    }

    return true;
}
